package com.xxxx.comment.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xxxx.comment.constants.RedisConstants;
import com.xxxx.comment.entity.dto.UserDTO;
import com.xxxx.comment.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lzf
 * @date 2023/7/9 18:25:09
 */
public class LoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    // 不能使用spring的依赖注入，因为这个拦截器是由我们手动添加到Web中的
    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        // 获取session
//        HttpSession session = request.getSession();
//        // 获取存储的用户信息
//        UserDTO user = (UserDTO) session.getAttribute("user");
//
//        if (user == null)
//        {
//            response.setStatus(401);
//            // return false拦截请求
//            return false;
//        }
//        UserHolder.saveUser(user);

        // 获取请求头中的token
        System.out.println(Thread.currentThread() + "---------Access Url: " + request.getRequestURI());
        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            response.setStatus(403);
            return false;
        }
        // 基于token获取redis中的用户信息
        Map<Object, Object> entries = stringRedisTemplate.opsForHash()
                .entries(RedisConstants.LOGIN_USER_KEY + token);
        // 将用户信息(Hash数据)转为UserDto对象
        if (entries.isEmpty()) {
            response.setStatus(401);
            return false;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
        userDTO.setToken(token);
        UserHolder.saveUser(userDTO);
        // 刷新token有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token,
                RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }

}
